﻿using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using System.Threading;
using System.Net;

namespace 云起停车_岗亭端
{
    public class Response {
        public int code { get; set; }
        public string msg { get; set; }
        public object data { get; set; }

        override
        public string ToString()
        {
            JObject jobject = JObject.FromObject(this);
            return jobject.ToString();
        }

    }

    public static class Utils
    {

        private static string token= "";

        private static Loading loadingForm;

        private delegate void CloseDelegate();

        private static readonly HttpClient client = new HttpClient();

        public static async Task<Response> GetAsync(string url, JObject data=null)
        {
            string host= RtspPlayer.Properties.Settings.Default.接口地址;
            try
            {
                if (null != data) {
                    string srt = "";
                    foreach(string key in data.Properties()) {
                        srt = key +"="+ data.GetValue(key)+"&";
                    }
                    srt=srt.Substring(0, srt.Length - 1);
                    url = url + "?" + srt;
                }
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                client.DefaultRequestHeaders.TryAddWithoutValidation("x-requested-with", "XMLHttpRequest");
                client.DefaultRequestHeaders.TryAddWithoutValidation("token", token);
                HttpResponseMessage httpresponse = await client.GetAsync(host+url);
                httpresponse.EnsureSuccessStatusCode();
                Task<string> task = httpresponse.Content.ReadAsStringAsync();
                JObject result = JObject.Parse(task.Result);
                Response response = result.ToObject<Response>();
                return response;
            }
            catch (HttpRequestException ex)
            {
                Form2.getInstance().Close();
                Console.WriteLine(ex.Message);
                Log(ex.Message);
                MessageBox.Show("请求异常，请检查配置");
                return null;
            }
        }

        public static async Task<Response> PostAsync(string url, JObject data,Form form)
        {
            string host = RtspPlayer.Properties.Settings.Default.接口地址;
            form.Enabled = false;
            ShowLoading();
            try
            {
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                StringContent content = new StringContent(data.ToString(), Encoding.UTF8, "application/json");
                client.DefaultRequestHeaders.TryAddWithoutValidation("x-requested-with", "XMLHttpRequest");
                client.DefaultRequestHeaders.TryAddWithoutValidation("token", token);
                HttpResponseMessage httpresponse = await client.PostAsync(host+url, content);
                httpresponse.EnsureSuccessStatusCode();
                Task<string> task= httpresponse.Content.ReadAsStringAsync();
                Console.WriteLine(task.Result);
                JObject result = JObject.Parse(task.Result);
                Response response = result.ToObject<Response>();
                if (response.code == 0)
                {
                    form.Enabled = true;
                    CloseLoading();
                    if (response.msg != null && !response.msg.Equals(""))
                    {
                        MessageBox.Show(response.msg);
                    }
                    return null;
                }
                form.Enabled = true;
                if (url.Equals("sentrybox/index/login")) {
                    JObject jobj = (JObject)response.data;
                    token = (string)jobj.GetValue("token");
                }
                CloseLoading();
                return response;
            }
            catch (HttpRequestException ex)
            {
                Form2.getInstance().Close();
                Console.WriteLine(ex.Message);
                form.Enabled = true;
                CloseLoading();
                Log(ex.Message);
                MessageBox.Show("请求异常，请检查配置");
                return null;
            }
        }

        public static async Task<Image> LoadImageFromUrlAsync(string url)
        {
            Console.WriteLine(url);
            using (HttpClient client = new HttpClient())
            {
                // 下载图片数据
                try
                {
                    byte[] imageData = await client.GetByteArrayAsync(url);
                    // 将数据转换为 MemoryStream
                    using (MemoryStream ms = new MemoryStream(imageData))
                    {
                        // 从流中加载图片
                        return Image.FromStream(ms);
                    }
                }
                catch (Exception ex){
                    Console.WriteLine(ex.Message);
                    return RtspPlayer.Properties.Resources.nopic;
                }
            }
        }

        public static void Log(string message)
        {
            string logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log.txt");
            File.AppendAllText(logFilePath, $"{DateTime.Now}: {message}{Environment.NewLine}");
        }

        /// <summary>
        /// 显示loading框
        /// </summary>
        public static void ShowLoading()
        {
            // Make sure it is only launched once.
            if (loadingForm != null)
            {
                return;
            }
            var thread = new Thread(ShowForm);
            thread.IsBackground = true;
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }

        /// <summary>
        /// 关闭窗口
        /// </summary>
        public static void CloseLoading()
        {
            while (loadingForm == null)
            {
                Thread.Sleep(50);
            }
            loadingForm.Invoke(new CloseDelegate(CloseFormInternal));
        }

        /// <summary>
        /// 显示窗口
        /// </summary>
        private static void ShowForm()
        {
            if (loadingForm != null)
            {
                loadingForm.closeOrder();
                loadingForm = null;
            }

            loadingForm = new Loading()
            {
                Visible = false,
                Width = 250,
                Height = 250,
                StartPosition = FormStartPosition.CenterScreen,
                // 设置窗体透明
                FormBorderStyle = FormBorderStyle.None,
                BackColor = Color.White,
                TransparencyKey = Color.White,
                ShowInTaskbar = false,
                ControlBox = false,
                MaximizeBox = false,
                MinimizeBox = false,
                TopMost = true,
            };
            // 添加一个加载动画（可选）
            var pictureBox = new PictureBox
            {
                Dock = DockStyle.Fill,
                Image = RtspPlayer.Properties.Resources.loading, // 请替换为你的加载动画图片
                SizeMode = PictureBoxSizeMode.StretchImage,
                BackColor = Color.Transparent
            };
            loadingForm.Controls.Add(pictureBox);
            loadingForm.ShowDialog();
        }

        private static void CloseFormInternal()
        {
            loadingForm.closeOrder();
            loadingForm = null;
        }
    }
}
